package com.nhutcm.trackingthief.service;

import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.WindowManager;

import com.nhutcm.trackingthief.R;
import com.nhutcm.trackingthief.receiver.TrackingThiefReceiver;
import com.nhutcm.trackingthief.utils.Constant;
import com.nhutcm.trackingthief.utils.PrefUtils;
import com.nhutcm.trackingthief.utils.ReceiverUtils;
import com.nhutcm.trackingthief.utils.RootUtils;

public class TrackingThiefService extends Service implements Callback {

	public static final String TAG = "com.nhutcm.trackingthief.service.TrackingThiefService";
	public static boolean isCaptureImage = false;

	CountDownTimer restartServiceTimer;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		/**
		 * Register receiver for config screen
		 */
		if (Constant.currentReceiver == null) {
			String code = PrefUtils.readStringFromPreference(
					getApplicationContext(), getString(R.string.pref_code_key));
			if (code.equals("")) {
				code = Constant.DEDAULT_SECRECT_CODE;
				PrefUtils.saveStringToPreference(getApplicationContext(),
						getString(R.string.pref_code_key),
						Constant.DEDAULT_SECRECT_CODE);
			}
			ReceiverUtils.registerSecretReceiver(getApplicationContext(), code);

		}

		/**
		 * Check phone state
		 */

		String statusPhone = PrefUtils.readStringFromPreference(
				getApplicationContext(), getString(R.string.phone_state));

		if (statusPhone.equals("0")) {
			Log.e(TAG, "Phone is LOST");
			if (!isCaptureImage) {
				captureImage();
			}

		} else {
			Log.e(TAG, "Phone is OK");
		}


		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		/** Timer auto start service again */
		restartServiceTimer = new CountDownTimer(Constant.HAFT_MINUTE,
				Constant.ONE_SECOND) {

			@Override
			public void onTick(long millisUntilFinished) {
			}

			@Override
			public void onFinish() {
				startService(new Intent(getApplicationContext(),
						TrackingThiefService.class));
				stopTimer();
			}
		}.start();

		super.onDestroy();
	}

	public void stopTimer() {
		if (restartServiceTimer != null) {
			restartServiceTimer.cancel();
			restartServiceTimer = null;
		}
	}

	/************************************************************/
	/************************************************************/
	/********************* Camera API ******************************/
	/************************************************************/
	/************************************************************/

	private Camera cameraObject;
	private SurfaceHolder holdMe;
	private SurfaceView surView;
	private WindowManager windowManager;
	private CountDownTimer timer;

	private void captureImage() {
		isCaptureImage = true;
		surView = new SurfaceView(this);
		windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

		if (cameraObject == null) {
			cameraObject = isCameraAvailiable();
			if (cameraObject == null) {
				showDialog(getApplicationContext());
				return;
			} else {
				Log.i(TAG, "cameraObject is READY");
			}
		}

		WindowManager.LayoutParams params = new WindowManager.LayoutParams(1,
				1, WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);

		params.gravity = Gravity.TOP | Gravity.LEFT;
		params.x = 0;
		params.y = 0;

		windowManager.addView(surView, params);

		holdMe = surView.getHolder();
		holdMe.addCallback(this);

		timer = new CountDownTimer(Constant.TWENTY_SECOND, Constant.FILE_SECOND) {

			@Override
			public void onTick(long arg0) {
				RootUtils.deleteIfExist(Constant.CAMERA_CLICK_ORR);
				cameraObject.takePicture(null, null, capturedIt);
			}

			@Override
			public void onFinish() {

				releaseCamera();
				if (surView != null)
					windowManager.removeView(surView);

				Intent intent = new Intent();
				intent.setAction(TrackingThiefReceiver.TRACKING_THIEF_RECEIVER);
				intent.putExtra(TrackingThiefReceiver.TASK_TYPE,
						Constant.TASK_CAPTURE_PHOTO_THIEF_COMPLETE);
				sendBroadcast(intent);
			}
		};
		timer.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (cameraObject != null && holder.getSurface() != null) {
			try {
				cameraObject.setPreviewDisplay(holder);
			} catch (IOException e) {
				e.getMessage();
			}
		}
		cameraObject.startPreview();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		if (cameraObject != null) {
			cameraObject.stopPreview();
		}
	}

	void releaseCamera() {
		if (cameraObject != null) {
			cameraObject.stopPreview();
			cameraObject.release();
			cameraObject = null;

			isCaptureImage = false;
		}
	}

	private PictureCallback capturedIt = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

			long time = System.currentTimeMillis();
			String fileDirsPath = PrefUtils.readStringFromPreference(
					getApplicationContext(), getString(R.string.file_path));

			String filename = fileDirsPath + "/" + String.valueOf(time)
					+ ".png";
			FileOutputStream out = null;

			try {
				out = new FileOutputStream(filename);
				bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (Throwable ignore) {
				}
			}

			cameraObject.startPreview();
		}
	};

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	public static Camera isCameraAvailiable() {
		Camera object = null;
		try {
			object = Camera.open(1);
		} catch (Exception e) {
		}
		return object;
	}

	@SuppressWarnings("deprecation")
	public static void showDialog(Context context) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();
		alertDialog.setMessage("The front camera is NOT-available.");
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		alertDialog.show();
	}
}
